package joe.beer;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;

import android.app.Activity;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Typeface;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.text.format.Time;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.TimePicker;

public class BeerActivity extends Activity {
	static final int MY_DIALOG_ID = 1; // id to uniquely identify this dialog in
										// onCreateDialog

	TableLayout tl;
	MySQLiteHelper dbHelper;
	CustomDrawableView cv;
	Handler mHandler;

	private int numDrinks = 0;
	private String bacLevel = "0.08";
	private String timeUntilSober = ".10";
	int _startHour, _startMinute;
	ArrayList<Beer> drankBeer = new ArrayList<Beer>();
	String el = "";
	long startTime;
	Person p;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		dbHelper = new MySQLiteHelper(this);

		tl = (TableLayout) findViewById(R.id.bacLayout);
		cv = new CustomDrawableView(this);
		tl.addView(
				cv,
				new TableLayout.LayoutParams(
						(int) Math.round(tl.getWidth() * .9), 140));
		tl.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.TOP);

		Button button = (Button) findViewById(R.id.button1);
		button.setOnClickListener(refreshUI);

		Button button2 = (Button) findViewById(R.id.button2);
		button2.setOnClickListener(openViewListener);

		Button button3 = (Button) findViewById(R.id.button3);
		button3.setOnClickListener(profileButton);

		Button button4 = (Button) findViewById(R.id.button4);
		button4.setOnClickListener(clearListener);

		Button button5 = (Button) findViewById(R.id.button5);
		button5.setOnClickListener(timeListener);
		
		Button button6 = (Button) findViewById(R.id.button6);
		button6.setOnClickListener(addNewBeerListener);

		mHandler = new Handler();
		mHandler.post(mUpdate);

		p = new Person(165, 1);
		
		startTime = dbHelper.getTime();
		if (startTime == 0)
		{
			startTime = System.currentTimeMillis();
		}
	}

	private void updateFields() {
		el = Compute.getTimeDifference(System.currentTimeMillis(), startTime);
		numDrinks = dbHelper.getCount();
		bacLevel = Compute
				.calculateBac(p, dbHelper.getPureAlcohol(), startTime);
		timeUntilSober = Compute.timeUntilSober(p, dbHelper.getPureAlcohol(),
				startTime);
		cv.invalidate();
	}

	// think of this override method like a dialog creation factory
	// where all your dialogs are defined
	@Override
	protected Dialog onCreateDialog(int id) {
		Calendar calendar = new GregorianCalendar();
		int hour = calendar.get(Calendar.HOUR);
		int minute = calendar.get(Calendar.MINUTE);
		return new TimePickerDialog(this, mTimeSetListener, hour, minute, false);
	}

	private TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
			// implement code to use the hourOfDay and
			// minute returned from the dialog
			Calendar calendar = Calendar.getInstance();
			Time t = new Time();
			t.set(0, minute, hourOfDay, calendar.get(Calendar.DAY_OF_MONTH),
					calendar.get(Calendar.MONTH), calendar.get(Calendar.YEAR));
			dbHelper.AddTime(t.toMillis(false));
			startTime = dbHelper.getTime();
			updateFields();
		}
	};

	// Create an anonymous implementation of OnClickListener
	private OnClickListener profileButton = new OnClickListener() {
		public void onClick(View v) {
			Intent myIntent = new Intent(BeerActivity.this,
					ProfileActivity.class);
			startActivityForResult(myIntent, 1);
		}
	};

	// Create an anonymous implementation of OnClickListener
	private OnClickListener refreshUI = new OnClickListener() {
		public void onClick(View v) {
			Intent myIntent = new Intent(BeerActivity.this,
					AddBeerActivity.class);
			startActivityForResult(myIntent, 1);
		}
	};

	// Create an anonymous implementation of OnClickListener
	private OnClickListener openViewListener = new OnClickListener() {
		public void onClick(View v) {
			Intent myIntent2 = new Intent(BeerActivity.this,
					ViewBeersActivity.class);
			startActivity(myIntent2);
		}
	};
	
	// Create an anonymous implementation of OnClickListener
	private OnClickListener addNewBeerListener = new OnClickListener() {
		public void onClick(View v) {
			Intent myIntent2 = new Intent(BeerActivity.this,
					AddNewBeerActivity.class);
			startActivity(myIntent2);
		}
	};

	// Create an anonymous implementation of OnClickListener
	private OnClickListener timeListener = new OnClickListener() {
		public void onClick(View v) {
			// Intent myIntent2 = new Intent(BeerActivity.this,
			// StartTimeActivity.class);
			// startActivityForResult(myIntent2,1);
			showDialog(MY_DIALOG_ID);
		}
	};

	// Create an anonymous implementation of OnClickListener
	private OnClickListener clearListener = new OnClickListener() {
		public void onClick(View v) {
			dbHelper.clearDrinks();
			startTime = System.currentTimeMillis();
			updateFields();
		}
	};

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK && requestCode == 1) {
			if (data.hasExtra("hour"))
				_startHour = Integer.parseInt(data.getExtras()
						.getString("hour"));
			if (data.hasExtra("minute")) {
				_startMinute = Integer.parseInt(data.getExtras().getString(
						"minute"));
				// tv.setText(_startHour + _startMinute);
			}

			if (data.hasExtra("weight")) {
				String weight = data.getExtras().getString("weight");
				p.setWeight(Integer.parseInt(weight));
			}

			if (data.hasExtra("sex")) {
				p.setSex(data.getExtras().getInt("sex"));
			}

		}
		updateFields();
	}

	public class CustomDrawableView extends View {
		private GradientDrawable mDrawable;
		Display display = getWindowManager().getDefaultDisplay();
		private int gWidth = display.getWidth() - 10;
		private int gHeight = 125;

		public CustomDrawableView(Context context) {
			super(context);
			int x = 10;
			int y = 10;
			Resources mResource = this.getResources();
			mDrawable = (GradientDrawable) mResource
					.getDrawable(R.drawable.bacbox);
			mDrawable.setBounds(x, y, gWidth, gHeight);
		}

		protected void onDraw(Canvas canvas) {

			mDrawable.draw(canvas);
			// Custom TypeFace
			Typeface tf = Typeface.createFromAsset(getAssets(),
					"fonts/Molot.otf");
			drawText(String.format("%1$s", String.valueOf(bacLevel)), canvas,
					Color.YELLOW, tf, 75, 25, 90);
			drawText(
					String.format("Number of Drinks Consumed: %1$s", numDrinks),
					canvas, Color.GRAY, Typeface.DEFAULT, 15, 210, 40);
			// NEXT IMPLEMENTATION NEED TO GET THE TIME SYNCHED
			drawText(String.format("Total Drinking Time: %1$s", el), canvas,
					Color.GRAY, Typeface.DEFAULT, 15, 210, 70);
			drawText(String.format("Time Until Sober: %s", timeUntilSober),
					canvas, Color.GRAY, Typeface.DEFAULT, 15, 210, 100);

		}

		private void drawText(String text, Canvas canvas, int color,
				Typeface tf, int fontSize, int x, int y) {

			Paint paint = new Paint();
			paint.setStyle(Style.FILL);
			paint.setColor(color);
			paint.setTypeface(tf);
			paint.setTextSize(fontSize);
			canvas.drawText(text, x, y, paint);

		}

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (dbHelper != null) {
			dbHelper.close();
		}
	}

	private Runnable mUpdate = new Runnable() {
		public void run() {
			mHandler.postDelayed(this, 10000);
			updateFields();
		}
	};
}